<?php
//рус
include_once(_CORE_PATH. "mapper_prototype.php");
class ServiceMapper extends mapper_prototype
{
	public function __construct()
	{
		parent::__construct('service');
	}	
	
	static public function GetInstance()
	{
		return new self();		
	}	
	
    public function DeleteHTMLCache()
    {
        $this->DeleteCache(MozgCfg::GetProp('global//styleCachePath'), 'html');
        return true;         
    }	
	
    public function DeleteCSSCache()
    {
        $this->DeleteCache(MozgCfg::GetProp('global//styleCachePath'), 'css');
        return true;         
    }
    
    public function DeleteJSCache()
    {
        $this->DeleteCache(MozgCfg::GetProp('global//styleCachePath'), 'js');
        return true;              
    }
    
    public function DeleteTMPCache()
    {
        $this->DeleteCache(MozgCfg::GetProp('global//tmpCachePath'), 'tmp');
        return true;              
    }  

    private function DeleteCache($path, $type = 'css')
    {
    	$gzExtensions = MozgCfg::GetProp('global//gzExtensions');
    	
        switch ($type)
        {
            case 'html':
                    $exts = array('html', $gzExtensions['html']);
                break;        	
        	
            case 'css':
                    $exts = array('css', $gzExtensions['css']);
                break;
                
            case 'js':
                    $exts = array('js', $gzExtensions['js']);
                break;

            case 'tmp':
                    $exts = array('phtml');
                break;                
                
            default: throw new Exception("Неизвестный тип файлов");                
        }
        
        $this->DelFilesByType($path, $exts);     
    }
    
    private function DelFilesByType($dir, $exts = array())
    {
        $totalFiles = 0; 
        
        $dir = rtrim($dir, '/');
        if (!is_dir($dir)) return true;
        if($handler = opendir($dir)) 
        {
            while (($sub = readdir($handler)) !== FALSE) 
            {
                if ($sub == "." || $sub == "..") continue;
                 
                $totalFiles++;
                
                if(is_file($dir."/".$sub)) 
                {
                    if (in_array(pathinfo($sub, PATHINFO_EXTENSION), $exts))
                    {
                        if (unlink($dir."/".$sub)) $totalFiles--;                                        
                    }
                }
                elseif(is_dir($dir."/".$sub))
                {                    
                    if ($this->DelFilesByType($dir."/".$sub, $exts)) $totalFiles--; 
                }
            }   
            closedir($handler);
            if (!$totalFiles && rmdir($dir)) return true;
        } 
    }     
}